﻿namespace WinEACProxy
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;

    using System.Text;
    using System.Windows.Forms;
    using EACProxy.Console;
    using System.Threading;

    public partial class EACProxyForm : Form
    {
        private Thread workerThread;
        private string url = "http://freedb.freedb.org:80/~cddb/cddb.cgi";
        private Proxy p;
        public EACProxyForm()
        {
            InitializeComponent();
            
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void p_Status(object sender, StatusEventArgs e)
        {
            ShowStatus(e.Message);
        }

        private void Listen()
        {            
            try
            {
                p = new Proxy()
                {
                    Port = this.port,
                    Url = this.url
                };
                p.Status += new EventHandler<StatusEventArgs>(p_Status);
                p.Listen();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("EACProxy: " + ex.ToString());
                ShowStatus("ERROR:" + ex.Message);
            }
        }

        private delegate void StringDelegate(string s);

        private void ShowStatus(string message)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new StringDelegate(ShowStatus), message);
            }
            else
            {
                statusLabel.Text = message;
            }
        }

        private void buttonGo_Click(object sender, EventArgs e)
        {
            buttonGo.Enabled = false;
            workerThread = new Thread(new ThreadStart(Listen));
            workerThread.IsBackground = true;
            workerThread.Start();

        }

        private int port = 16322;
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (!int.TryParse(textBoxPort.Text, out port))
            {
                ShowStatus("Invalid port - should be a number");
            }
        }

        private void textBoxUrl_TextChanged(object sender, EventArgs e)
        {
            this.url = textBoxUrl.Text;
        }
    }
}
